import { Ionicons } from "@expo/vector-icons";
import {
  Canvas,
  Group,
  Image,
  Matrix4,
  Path,
  Rect,
  Skia,
  Text,
  useCanvasRef,
  useFont,
  useImage,
} from "@shopify/react-native-skia";
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import {
  Dimensions,
  Image as RNImage,
  StyleSheet,
  TouchableOpacity,
  View
} from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import {
  useAnimatedStyle,
  useDerivedValue,
  useSharedValue,
  withTiming
} from "react-native-reanimated";

import { Layer } from "../imageEditor/types";
import { CanvasMenu } from "./CanvasMenu";
import { GridGestureHandler } from "./GridGestureHandler";
import { CanvasSize, GridCell, GridLayout } from "./LayoutEditor";
import { UniversalGestureHandler } from "./UniversalGestureHandler";

// 宫格单元格接口 - 使用从 LayoutEditor 导入的接口

const { width: screenWidth, height: screenHeight } = Dimensions.get("window");

// 画布状态接口
interface CanvasState {
  layers: Layer[];
  width: number;
  height: number;
  backgroundColor: string;
  backgroundImage?: string;
  backgroundGradient?: string[];
  backgroundPattern?: string;
  selectedLayerId?: string;
  gridLayout?: GridLayout;
  canvasSize: CanvasSize;
  selectedGridCell?: GridCell; // 新增：选中的宫格单元格
  // 网格权重：用于动态调整每列/每行的宽高占比
  columnWeights?: number[];
  rowWeights?: number[];
}

// 图层控制按钮组件
interface LayerControlButtonsProps {
  layer: Layer;
  onDelete: (layerId: string) => void;
  onCopy: (layerId: string) => void;
  onLock: (layerId: string) => void;
  onVisibility: (layerId: string) => void;
}

const LayerControlButtons: React.FC<LayerControlButtonsProps> = ({
  layer,
  onDelete,
  onCopy,
  onLock,
  onVisibility,
}) => {
  if (!layer.visible) return null;

  // 计算按钮位置，基于图层位置
  const buttonPosition = {
    top: (layer.data.y || 0) - 40, // 在图层上方
    left: (layer.data.x || 0) + (layer.data.width || 100) - 120, // 在图层右上角
  };

  return (
    <View style={[styles.controlButtons, buttonPosition]}>
      <TouchableOpacity
        style={styles.controlButton}
        onPress={() => onVisibility(layer.id)}
      >
        <Ionicons
          name={layer.visible ? "eye" : "eye-off"}
          size={16}
          color="#fff"
        />
      </TouchableOpacity>

      <TouchableOpacity
        style={styles.controlButton}
        onPress={() => onLock(layer.id)}
      >
        <Ionicons
          name={layer.locked ? "lock-closed" : "lock-open"}
          size={16}
          color="#fff"
        />
      </TouchableOpacity>

      <TouchableOpacity
        style={styles.controlButton}
        onPress={() => onCopy(layer.id)}
      >
        <Ionicons name="copy" size={16} color="#fff" />
      </TouchableOpacity>

      <TouchableOpacity
        style={styles.controlButton}
        onPress={() => onDelete(layer.id)}
      >
        <Ionicons name="trash" size={16} color="#fff" />
      </TouchableOpacity>
    </View>
  );
};

// 自由拼图画布组件属性
interface FreePuzzleCanvasProps {
  onSave?: () => void;
  onCancel?: () => void;
  disabled?: boolean;
  backgroundColor?: string;
  canvasWidth?: number;
  canvasHeight?: number;
  onCanvasMenuSelect?: (
    menuType: "photo" | "sticker" | "background" | "text"
  ) => void;
}

// 画布操作接口
export interface FreePuzzleCanvasRef {
  // 图层管理
  getLayers: () => Layer[];
  setLayers: (layers: Layer[]) => void;
  addLayer: (layer: Omit<Layer, "id" | "zIndex">) => void;
  removeLayer: (layerId: string) => void;
  toggleLayerVisibility: (layerId: string) => void;
  toggleLayerLock: (layerId: string) => void;
  getSelectedLayer: () => string | undefined;
  selectLayer: (layerId?: string) => void;

  // 内容添加
  addText: (textData: any) => void;
  addSticker: (stickerData: any) => void;
  addImage: (imageData: any) => void;
  addVideo: (videoData: any) => void;

  // 画布操作
  clearCanvas: () => void;
  setBackgroundColor: (color: string) => void;
  setBackgroundImage: (imageUri: string) => void;
  setBackgroundGradient: (gradient: string[]) => void;
  setBackgroundPattern: (pattern: string) => void;
  setCanvasSize: (size: CanvasSize) => void;
  setGridLayout: (grid: GridLayout) => void;

  // 网格操作（已移除自动填充图片）

  // 层级操作
  moveLayerUp: (layerId: string) => void;
  moveLayerDown: (layerId: string) => void;
  moveLayerToTop: (layerId: string) => void;
  moveLayerToBottom: (layerId: string) => void;

  // 编辑操作
  copyLayer: (layerId: string) => void;
  deleteLayer: (layerId: string) => void;
  transformLayer: (layerId: string, transform: any) => void;

  // 历史记录
  undo: () => void;
  redo: () => void;
  canUndo: () => boolean;
  canRedo: () => boolean;

  // 相框和蒙版操作
  applyFrameToLayer: (layerId: string, frame: any) => void;
  applyFrameSettingsToLayer: (layerId: string, settings: any) => void;
  applyMaskToLayer: (layerId: string, mask: any) => void;
  applyMaskSettingsToLayer: (layerId: string, settings: any) => void;

  // 导出功能
  exportCanvas: () => Promise<string>;
}

/**
 * 自由拼图画布组件
 * 基于 React Native Skia 实现的画布，支持图层管理、文字、贴纸等功能
 */
const FreePuzzleCanvas = forwardRef<FreePuzzleCanvasRef, FreePuzzleCanvasProps>(
  (
    {
      disabled = false,
      backgroundColor = "rgba(0,0,0,0)",
      canvasWidth,
      canvasHeight,
      onCanvasMenuSelect,
    },
    ref
  ) => {
    const canvasRef = useCanvasRef();

    // 计算画布尺寸：使用容器的实际可用空间
    const calculateCanvasSize = (
      containerWidth: number,
      containerHeight: number,
      aspectRatio: number = 1
    ) => {
      // 计算在容器内按比例适配的最大尺寸
      // 确保画布在容器内最大化显示，同时保持比例
      // 使用容器的实际尺寸，不添加额外的安全边距

      let finalWidth, finalHeight;

      // 计算按宽度适配的高度
      const heightByWidth = containerWidth / aspectRatio;

      // 计算按高度适配的宽度
      const widthByHeight = containerHeight * aspectRatio;

      if (heightByWidth <= containerHeight) {
        // 按宽度适配，高度不会超出容器
        finalWidth = containerWidth;
        finalHeight = heightByWidth;
      } else {
        // 按高度适配，宽度不会超出容器
        finalWidth = widthByHeight;
        finalHeight = containerHeight;
      }

      return { width: finalWidth, height: finalHeight };
    };

    // 使用容器的实际尺寸，不进行固定减法
    const defaultContainerWidth = screenWidth;
    const defaultContainerHeight = screenHeight;

    // 计算默认画布尺寸
    const defaultCanvasSize = calculateCanvasSize(
      defaultContainerWidth,
      defaultContainerHeight,
      1
    );

    // 优先使用计算出的尺寸，只有在没有计算尺寸时才使用props的尺寸
    const finalCanvasWidth = defaultCanvasSize.width || canvasWidth || 384;
    const finalCanvasHeight = defaultCanvasSize.height || canvasHeight || 384;

    // 默认画布尺寸对象
    const defaultCanvasSizeObj: CanvasSize = {
      key: "1:1",
      label: "正方形",
      aspectRatio: 1,
      width: finalCanvasWidth,
      height: finalCanvasHeight,
    };

    // 画布状态
    const [canvasState, setCanvasState] = useState<CanvasState>({
      layers: [],
      width: finalCanvasWidth,
      height: finalCanvasHeight,
      backgroundColor: backgroundColor,
      canvasSize: defaultCanvasSizeObj,
      columnWeights: [1, 1, 1, 1],
      rowWeights: [1, 1, 1, 1],
    });

    // 历史记录
    const [history, setHistory] = useState<CanvasState[]>([canvasState]);
    const [historyIndex, setHistoryIndex] = useState(0);

    // 图片处理队列
    const [pendingImages, setPendingImages] = useState<any[]>([]);
    const [isProcessingImages, setIsProcessingImages] = useState(false);

    // 移除containerSize状态，直接使用canvasState的width和height

    // 添加一个状态来存储layerContainer的实际尺寸
    const [layerContainerSize, setLayerContainerSize] = useState({
      width: screenWidth,
      height: screenHeight,
    });

    // 监听画布尺寸变化 - 移除这个useEffect，避免覆盖计算出的尺寸

    // 动态计算画布尺寸的函数
    const updateCanvasSize = useCallback(
      (containerWidth: number, containerHeight: number) => {
        // 根据容器尺寸与当前画布宽高比，实时计算并更新画布尺寸
        const currentAspectRatio = canvasState.canvasSize?.aspectRatio || 1;
        const newSize = calculateCanvasSize(
          containerWidth,
          containerHeight,
          currentAspectRatio
        );

        setCanvasState((prev) => ({
          ...prev,
          width: newSize.width,
          height: newSize.height,
        }));
      },

      [canvasState.canvasSize?.aspectRatio] // 依赖项调整
    );

    // 画布菜单状态
    const [showCanvasMenu, setShowCanvasMenu] = useState(false);
    const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });

    // 手势相关状态
    const [selectedLayerId, setSelectedLayerId] = useState<string | null>(null);
    const [selectedGridCell, setSelectedGridCell] = useState<{
      row: number;
      col: number;
    } | null>(null);
    const [layerMatrices, setLayerMatrices] = useState<Record<string, any>>({});
    const [gridVersion, setGridVersion] = useState(0);

    // 初始化图层矩阵
    useEffect(() => {
      const newMatrices: Record<string, any> = {};
      canvasState.layers.forEach((layer) => {
        if (!layerMatrices[layer.id]) {
          // 创建包含旋转和缩放的矩阵
          const m = Skia.Matrix();
          const rotation = layer.data.rotation || 0;
          const scale = layer.data.scale || 1;
          const centerX = (layer.data.x || 0) + (layer.data.width || 100) / 2;
          const centerY = (layer.data.y || 0) + (layer.data.height || 100) / 2;

          // 移动到中心点，缩放，旋转，再移回原位置（与 Skia 渲染一致）
          m.translate(centerX, centerY);
          m.scale(scale, scale);
          m.rotate((rotation * Math.PI) / 180); // 转换为弧度
          m.translate(-centerX, -centerY);

          newMatrices[layer.id] = { value: m as any };
        } else {
          newMatrices[layer.id] = layerMatrices[layer.id];
        }
      });

      if (Object.keys(newMatrices).length > 0) {
        setLayerMatrices((prev) => ({ ...prev, ...newMatrices }));
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [canvasState.layers]);

    // 实时更新图层矩阵（当图层变换时）
    useEffect(() => {
      const updatedMatrices: Record<string, any> = {};
      canvasState.layers.forEach((layer) => {
        const rotation = layer.data.rotation || 0;
        const scale = layer.data.scale || 1;
        const x = layer.data.x || 0;
        const y = layer.data.y || 0;
        const width = layer.data.width || 100;
        const height = layer.data.height || 100;

        // 计算中心点
        const centerX = x + width / 2;
        const centerY = y + height / 2;

        // 创建新的变换矩阵
        const m = Skia.Matrix();
        m.translate(centerX, centerY);
        m.scale(scale, scale);
        m.rotate((rotation * Math.PI) / 180);
        m.translate(-centerX, -centerY);

        updatedMatrices[layer.id] = { value: m as any };
      });

      setLayerMatrices(updatedMatrices);
    }, [canvasState.layers]);

    // 为每个图层创建手势信号
    const layerSelectSignal = useSharedValue<{
      layerId: string;
      timestamp: number;
    } | null>(null);
    const layerDeleteSignal = useSharedValue<{
      layerId: string;
      timestamp: number;
    } | null>(null);
    const layerEditSignal = useSharedValue<{
      layerId: string;
      timestamp: number;
    } | null>(null);
    const layerTransformSignal = useSharedValue<{
      layerId: string;
      x?: number;
      y?: number;
      rotation?: number;
      scale?: number;
      timestamp: number;
    } | null>(null);

    // 字体管理
    const font = useFont(null, 16);

    // 背景图片 - 安全加载
    const backgroundImage = useImage(canvasState.backgroundImage || "");

    // 手势事件共享值（UI 线程）
    const selectedCellSV = useSharedValue<{ row: number; col: number } | null>(
      null
    );
    const selectedRectSV = useSharedValue<{
      x: number;
      y: number;
      width: number;
      height: number;
    } | null>(null);
    const doubleTapSignalSV = useSharedValue(0);
    const menuVisibleSV = useSharedValue(0);
    const menuXSV = useSharedValue(0);
    const menuYSV = useSharedValue(0);
    // 清除交互上下文：选中、菜单等
    const clearInteractionContext = useCallback(() => {
      try {
        selectedCellSV.value = null;
        selectedRectSV.value = null;
        menuVisibleSV.value = 0;
      } catch {}
      setSelectedGridCell(null);
      setShowCanvasMenu(false);
      setSelectedLayerId(null); // 同时清除图层选中状态
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    // 尺寸/布局变化时，按当前网格重新计算选中区域（JS 侧直接写共享值，无需 runOnJS）
    const recomputeSelectedRect = useCallback(() => {
      const cell = selectedCellSV.value;
      const grid = canvasState.gridLayout;
      if (!cell || !grid || grid.key === "none") {
        selectedRectSV.value = null;
        return;
      }
      const { rows, cols } = grid;
      const outerMargin = 10; // 保持与网格渲染一致
      const spacing = 10;
      const actualWidth = canvasState.width;
      const actualHeight = canvasState.height;
      const widthAvailable =
        actualWidth - outerMargin * 2 - spacing * (cols - 1);
      const heightAvailable =
        actualHeight - outerMargin * 2 - spacing * (rows - 1);
      const colWidth = widthAvailable / cols;
      const rowHeight = heightAvailable / rows;
      const x = outerMargin + cell.col * (colWidth + spacing);
      const y = outerMargin + cell.row * (rowHeight + spacing);
      selectedRectSV.value = { x, y, width: colWidth, height: rowHeight };
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [canvasState.gridLayout, canvasState.width, canvasState.height]);

    // 监听尺寸/布局/选中cell变化
    useEffect(() => {
      recomputeSelectedRect();
    }, [recomputeSelectedRect]);

    // 监听选中状态变化，同步到 React 状态
    const selectedCellValue = useDerivedValue(() => {
      return selectedCellSV.value;
    });

    useEffect(() => {
      if (selectedCellValue.value === null) {
        // 清除选中状态
        setSelectedGridCell(null);
        setSelectedLayerId(null);
        setShowCanvasMenu(false);
      }
    }, [selectedCellValue.value]);

    // 监听图层手势信号
    useEffect(() => {
      const selectValue = layerSelectSignal.value;
      if (selectValue && selectValue.layerId) {
        setSelectedLayerId(selectValue.layerId);
        // 重置信号
        layerSelectSignal.value = null;
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [layerSelectSignal.value, canvasState.layers]);

    useEffect(() => {
      const deleteValue = layerDeleteSignal.value;
      if (deleteValue && deleteValue.layerId) {
        console.log("删除图层:", deleteValue.layerId);
        // 这里暂时只记录，实际的删除操作在 removeLayer 定义后处理
        // 重置信号
        layerDeleteSignal.value = null;
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [layerDeleteSignal.value, canvasState.layers]);

    useEffect(() => {
      const editValue = layerEditSignal.value;
      if (editValue && editValue.layerId) {
        console.log("编辑图层:", editValue.layerId);
        // 重置信号
        layerEditSignal.value = null;
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [layerEditSignal.value, canvasState.layers]);

    // 监听图层变换信号
    // 为每个图层创建变换的 SharedValue
    const layerTransforms = useSharedValue<{
      [layerId: string]: {
        x: number;
        y: number;
        rotation: number;
        scale: number;
      };
    }>({});

    // 监听变换信号，直接更新 layerTransforms
    useDerivedValue(() => {
      const transformValue = layerTransformSignal.value;
      if (transformValue && transformValue.layerId) {
        
        const currentTransform = layerTransforms.value[transformValue.layerId] || {
          x: 0,
          y: 0,
          rotation: 0,
          scale: 1,
        };

        // 直接使用手势层传来的数据，不进行任何计算
        layerTransforms.value = {
          ...layerTransforms.value,
          [transformValue.layerId]: {
            x: transformValue.x !== undefined ? transformValue.x : currentTransform.x,
            y: transformValue.y !== undefined ? transformValue.y : currentTransform.y,
            rotation: transformValue.rotation !== undefined ? transformValue.rotation : currentTransform.rotation,
            scale: transformValue.scale !== undefined ? transformValue.scale : currentTransform.scale,
          },
        };

        // 重置信号
        layerTransformSignal.value = null;
      }
    });

    // 选中高亮由 Skia 网格描边控制，这里不再使用覆盖层

    // 菜单样式（完全由共享值控制）
    const menuStyle = useAnimatedStyle(() => {
      const visible = menuVisibleSV.value;
      return {
        position: "absolute",
        left: menuXSV.value,
        top: menuYSV.value,
        opacity: withTiming(visible, { duration: 150 }),
        transform: [
          { scale: withTiming(visible ? 1 : 0.95, { duration: 150 }) },
        ],
        zIndex: 6,
      } as any;
    });

    // 生成唯一ID
    const generateId = () => {
      return `layer_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    };

    // 保存当前状态到历史记录
    const saveToHistory = useCallback(
      (newState: CanvasState) => {
        const newHistory = history.slice(0, historyIndex + 1);
        newHistory.push(newState);
        setHistory(newHistory);
        setHistoryIndex(newHistory.length - 1);
        setCanvasState(newState);
      },
      [history, historyIndex]
    );

    // 撤销操作
    const undo = useCallback(() => {
      if (historyIndex > 0) {
        const newIndex = historyIndex - 1;
        setHistoryIndex(newIndex);
        setCanvasState(history[newIndex]);
      }
    }, [history, historyIndex]);

    // 重做操作
    const redo = useCallback(() => {
      if (historyIndex < history.length - 1) {
        const newIndex = historyIndex + 1;
        setHistoryIndex(newIndex);
        setCanvasState(history[newIndex]);
      }
    }, [history, historyIndex]);

    // 当前最大层级记录
    const [currentMaxZIndex, setCurrentMaxZIndex] = useState(2); // 初始为宫格层级
    // 手势层层级记录
    const [gestureZIndex, setGestureZIndex] = useState(3); // 初始手势层层级

    // 添加图层
    const addLayer = useCallback(
      (layerData: Omit<Layer, "id" | "zIndex">, customZIndex?: number) => {
        setCanvasState((prevState) => {
          // 确保新图层的层级高于宫格（宫格 zIndex 是 2）
          const minZIndex = 3;
          // 使用自定义层级或计算新层级
          const newZIndex =
            customZIndex || Math.max(minZIndex, currentMaxZIndex + 1);

          const newLayer: Layer = {
            ...layerData,
            id: generateId(),
            zIndex: newZIndex,
          };

          // 如果是图片图层，自动创建对应的手势层
          let layersToAdd = [newLayer];
          if (layerData.type === "image") {
            const gestureLayer: Layer = {
              id: generateId(),
              name: "手势层",
              type: "gesture",
              locked: false,
              visible: true,
              zIndex: newZIndex, // 手势层和图片层使用相同层级
              data: {
                targetLayerId: newLayer.id,
                x: layerData.data?.x || 0,
                y: layerData.data?.y || 0,
                width: layerData.data?.width || 100,
                height: layerData.data?.height || 100,
                rotation: layerData.data?.rotation || 0,
                scale: layerData.data?.scale || 1,
              },
            };
            layersToAdd.push(gestureLayer);
          }

          const newState = {
            ...prevState,
            layers: [...prevState.layers, ...layersToAdd],
          };
          // 更新全局最大层级（为下一组预留空间）
          const nextMaxZIndex = newZIndex + 1;
          setCurrentMaxZIndex(nextMaxZIndex);

          // 保存到历史记录
          const newHistory = history.slice(0, historyIndex + 1);
          newHistory.push(newState);
          setHistory(newHistory);
          setHistoryIndex(newHistory.length - 1);

          return newState;
        });
      },

      [history, historyIndex, currentMaxZIndex]
    );

    // 添加文字
    const addText = useCallback(
      (textData: any) => {
        const textLayer: Omit<Layer, "id" | "zIndex"> = {
          name: "文字",
          type: "text",
          locked: false,
          visible: true,
          data: {
            text: textData.text || "新文字",
            x: canvasState.width / 2,
            y: canvasState.height / 2,
            fontSize: textData.fontSize || 24,
            color: textData.color || "#000000",
            fontFamily: textData.fontFamily || "System",
            ...textData,
          },
        };

        addLayer(textLayer);
      },
      [addLayer, canvasState.width, canvasState.height]
    );

    // 添加贴纸
    const addSticker = useCallback(
      (stickerData: any) => {
        // 检查贴纸数据格式
        if (!stickerData.icon) {
          console.log("Sticker data missing icon property:", stickerData);
          return;
        }

        // 对于SVG贴纸，我们需要创建一个临时的图像源
        // 这里我们使用一个占位符，实际应用中需要将SVG转换为图像
        const stickerLayer: Omit<Layer, "id" | "zIndex"> = {
          name: "贴纸",
          type: "sticker",
          locked: false,
          visible: true,
          data: {
            source: stickerData.icon
              ? `sticker://${stickerData.key}`
              : stickerData.source,
            icon: stickerData.icon, // 保存原始SVG组件
            key: stickerData.key,
            x: canvasState.width / 2,
            y: canvasState.height / 2,
            width: stickerData.width || 100,
            height: stickerData.height || 100,
            ...stickerData,
          },
        };

        addLayer(stickerLayer);
      },
      [addLayer, canvasState.width, canvasState.height]
    );

    // 添加图片
    const addImage = useCallback(
      (imageData: any) => {
        // 检查 imageData 是否包含多张图片
        const imagesToProcess = Array.isArray(imageData)
          ? imageData
          : [imageData];
        // 检查是否有重复的图片
        const imageSources = imagesToProcess.map((img) => img.source);
        const uniqueSources = [...new Set(imageSources)];
        if (imageSources.length !== uniqueSources.length) {
          // 去重处理
          const uniqueImages = imagesToProcess.filter(
            (img, index) => imageSources.indexOf(img.source) === index
          );
          imagesToProcess.length = 0;
          imagesToProcess.push(...uniqueImages);
        }
        // 将图片添加到待处理队列
        setPendingImages((prev) => [...prev, ...imagesToProcess]);
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [
        canvasState.width,
        canvasState.height,
        canvasState.layers,
        history,
        historyIndex,
      ]
    );

    // 添加视频
    const addVideo = useCallback(
      (videoData: any) => {
        const videoLayer: Omit<Layer, "id" | "zIndex"> = {
          name: "视频",
          type: "image", // 视频当作图片处理，显示封面
          locked: false,
          visible: true,
          data: {
            source: videoData.thumbnail || videoData.source,
            videoSource: videoData.source,
            x: canvasState.width / 2,
            y: canvasState.height / 2,
            width: videoData.width || 200,
            height: videoData.height || 200,
            scale: 1,
            rotation: 0,
            isVideo: true,
            ...videoData,
          },
        };

        addLayer(videoLayer);
      },
      [addLayer, canvasState.width, canvasState.height]
    );

    // 切换图层可见性
    const toggleLayerVisibility = useCallback(
      (layerId: string) => {
        const newLayers = canvasState.layers.map((layer) =>
          layer.id === layerId ? { ...layer, visible: !layer.visible } : layer
        );
        const newState = {
          ...canvasState,
          layers: newLayers,
        };

        saveToHistory(newState);
      },
      [canvasState, saveToHistory]
    );

    // 切换图层锁定状态
    const toggleLayerLock = useCallback(
      (layerId: string) => {
        const newLayers = canvasState.layers.map((layer) =>
          layer.id === layerId ? { ...layer, locked: !layer.locked } : layer
        );

        const newState = {
          ...canvasState,
          layers: newLayers,
        };

        saveToHistory(newState);
      },
      [canvasState, saveToHistory]
    );

    // 移除图层
    const removeLayer = useCallback(
      (layerId: string) => {
        const newLayers = canvasState.layers.filter(
          (layer) => layer.id !== layerId
        );

        const newState = {
          ...canvasState,
          layers: newLayers,
        };

        saveToHistory(newState);
      },
      [canvasState, saveToHistory]
    );

    // 清空画布
    const clearCanvas = useCallback(() => {
      const newState = {
        ...canvasState,
        layers: [],
      };

      saveToHistory(newState);
    }, [canvasState, saveToHistory]);

    // 设置背景颜色
    const setBackgroundColor = useCallback(
      (color: string) => {
        const newState = {
          ...canvasState,
          backgroundColor: color,
          backgroundImage: undefined, // 清除图片背景
          backgroundGradient: undefined, // 清除渐变背景
          backgroundPattern: undefined, // 清除图案背景
        };

        saveToHistory(newState);
      },
      [canvasState, saveToHistory]
    );

    // 设置画布尺寸
    const setCanvasSize = useCallback(
      (size: CanvasSize) => {
        // 使用layerContainer的实际尺寸
        const actualContainerWidth = layerContainerSize.width;
        const actualContainerHeight = layerContainerSize.height;

        // 根据新的宽高比重新计算画布尺寸
        const newSize = calculateCanvasSize(
          actualContainerWidth,
          actualContainerHeight,
          size.aspectRatio
        );

        // 切换尺寸前清除选中与菜单，并强制重建手势组件
        try {
          if (selectedCellSV) selectedCellSV.value = null;
          if (selectedRectSV) selectedRectSV.value = null;
          if (menuVisibleSV) menuVisibleSV.value = 0;
        } catch {}
        setSelectedGridCell(null);
        setGridVersion((v) => v + 1);

        const newState = {
          ...canvasState,
          width: newSize.width,
          height: newSize.height,
          canvasSize: size,
        };

        saveToHistory(newState);
      },
      [
        layerContainerSize.width,
        layerContainerSize.height,
        canvasState,
        saveToHistory,
        selectedCellSV,
        selectedRectSV,
        menuVisibleSV,
      ]
    );

    // 设置网格布局
    const setGridLayout = useCallback(
      (grid: GridLayout) => {
        // 切换宫格时清空选中与菜单（共享值 + React 状态）
        try {
          // 共享值存在时重置
          if (selectedCellSV) selectedCellSV.value = null;
          if (selectedRectSV) selectedRectSV.value = null;
          if (menuVisibleSV) menuVisibleSV.value = 0;
        } catch {}
        setSelectedGridCell(null);
        setGridVersion((v) => v + 1);

        const newState = {
          ...canvasState,
          gridLayout: grid,
        };

        saveToHistory(newState);
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [canvasState, saveToHistory]
    );

    // 选择图层
    const selectLayer = useCallback((layerId?: string) => {
      setCanvasState((prev) => ({
        ...prev,
        selectedLayerId: layerId,
      }));
    }, []);

    // 获取选中的图层
    const getSelectedLayer = useCallback(() => {
      return canvasState.selectedLayerId;
    }, [canvasState.selectedLayerId]);

    // 层级操作
    const moveLayerUp = useCallback(
      (layerId: string) => {
        const layers = [...canvasState.layers];
        const index = layers.findIndex((layer) => layer.id === layerId);
        if (index < layers.length - 1) {
          const layer = layers[index];
          layers[index] = layers[index + 1];
          layers[index + 1] = layer;

          // 更新zIndex
          layers.forEach((layer, i) => {
            layer.zIndex = i;
          });

          const newState = {
            ...canvasState,
            layers,
          };

          saveToHistory(newState);
        }
      },
      [canvasState, saveToHistory]
    );

    const moveLayerDown = useCallback(
      (layerId: string) => {
        const layers = [...canvasState.layers];
        const index = layers.findIndex((layer) => layer.id === layerId);
        if (index > 0) {
          const layer = layers[index];
          layers[index] = layers[index - 1];
          layers[index - 1] = layer;

          // 更新zIndex
          layers.forEach((layer, i) => {
            layer.zIndex = i;
          });

          const newState = {
            ...canvasState,
            layers,
          };

          saveToHistory(newState);
        }
      },
      [canvasState, saveToHistory]
    );

    const moveLayerToTop = useCallback(
      (layerId: string) => {
        const layers = [...canvasState.layers];
        const index = layers.findIndex((layer) => layer.id === layerId);
        if (index > -1) {
          const layer = layers.splice(index, 1)[0];
          layers.push(layer);

          // 更新zIndex
          layers.forEach((layer, i) => {
            layer.zIndex = i;
          });

          const newState = {
            ...canvasState,
            layers,
          };

          saveToHistory(newState);
        }
      },
      [canvasState, saveToHistory]
    );

    const moveLayerToBottom = useCallback(
      (layerId: string) => {
        const layers = [...canvasState.layers];
        const index = layers.findIndex((layer) => layer.id === layerId);
        if (index > -1) {
          const layer = layers.splice(index, 1)[0];
          layers.unshift(layer);

          // 更新zIndex
          layers.forEach((layer, i) => {
            layer.zIndex = i;
          });

          const newState = {
            ...canvasState,
            layers,
          };

          saveToHistory(newState);
        }
      },
      [canvasState, saveToHistory]
    );

    // 复制图层
    const copyLayer = useCallback(
      (layerId: string) => {
        const layer = canvasState.layers.find((l) => l.id === layerId);
        if (layer) {
          const newLayer: Layer = {
            ...layer,
            id: generateId(),
            name: `${layer.name} 副本`,
            zIndex: canvasState.layers.length,
            data: {
              ...layer.data,
              x: (layer.data.x || 0) + 20,
              y: (layer.data.y || 0) + 20,
            },
          };

          const newState = {
            ...canvasState,
            layers: [...canvasState.layers, newLayer],
          };

          saveToHistory(newState);
        }
      },
      [canvasState, saveToHistory]
    );

    // 删除图层
    const deleteLayer = useCallback(
      (layerId: string) => {
        removeLayer(layerId);
      },
      [removeLayer]
    );

    // 变换图层
    const transformLayer = useCallback(
      (layerId: string, transform: any) => {
        const newLayers = canvasState.layers.map((layer) => {
          if (layer.id === layerId) {
            return { ...layer, data: { ...layer.data, ...transform } };
          }
          // 如果是手势层，且目标图层被变换，同步更新手势层
          if (
            layer.type === "gesture" &&
            layer.data.targetLayerId === layerId
          ) {
            return { ...layer, data: { ...layer.data, ...transform } };
          }
          return layer;
        });

        const newState = {
          ...canvasState,
          layers: newLayers,
        };

        saveToHistory(newState);
      },
      [canvasState, saveToHistory]
    );

    // 导出画布
    const exportCanvas = useCallback(async (): Promise<string> => {
      if (canvasRef.current) {
        try {
          const image = canvasRef.current.makeImageSnapshot();
          if (image) {
            // 将SkImage转换为base64字符串
            const base64 = image.encodeToBase64();
            return `data:image/png;base64,${base64}`;
          }
        } catch (error) {
          console.error("导出画布失败:", error);
        }
      }
      throw new Error("无法导出画布");
    }, [canvasRef]);

    // 处理画布点击
    const handleCanvasTap = useCallback(
      (event: {
        x?: number;
        y?: number;
        absoluteX?: number;
        absoluteY?: number;
      }) => {
        "worklet";
        const localX = event.x ?? 0;
        const localY = event.y ?? 0;

        // 计算当前 Canvas 在容器中的左上角坐标
        const canvasLeft = (layerContainerSize.width - canvasState.width) / 2;
        const canvasTop = (layerContainerSize.height - canvasState.height) / 2;
        const inCanvasBounds =
          localX >= canvasLeft &&
          localX <= canvasLeft + canvasState.width &&
          localY >= canvasTop &&
          localY <= canvasTop + canvasState.height;

        // 如果在画布区域外，清除上下文并返回
        if (!inCanvasBounds) {
          clearInteractionContext();
          return;
        }

        // 将点击坐标转换为画布内部坐标
        const canvasX = localX - canvasLeft;
        const canvasY = localY - canvasTop;

        // 检查是否点击了可交互图层
        let clickedLayerId: string | null = null;
        for (let i = canvasState.layers.length - 1; i >= 0; i--) {
          const layer = canvasState.layers[i];
          if (layer.visible && !layer.locked) {
            const layerX = layer.data.x || 0;
            const layerY = layer.data.y || 0;
            const layerWidth = layer.data.width || 0;
            const layerHeight = layer.data.height || 0;

            if (
              canvasX >= layerX &&
              canvasX <= layerX + layerWidth &&
              canvasY >= layerY &&
              canvasY <= layerY + layerHeight
            ) {
              clickedLayerId = layer.id;
              break;
            }
          }
        }

        if (clickedLayerId) {
          // 选中图层，清除宫格选中
          selectLayer(clickedLayerId);
          clearInteractionContext();
        } else {
          // 点击画布背景（空白处）取消选中（图层与宫格）并隐藏菜单
          clearInteractionContext();
        }
      },
      [
        canvasState.layers,
        canvasState.width,
        canvasState.height,
        layerContainerSize,
        selectLayer,
        clearInteractionContext,
      ]
    );

    // 背景手势 - 专门用于检测画布空白区域的点击
    const backgroundGesture = Gesture.Tap()
      .shouldCancelWhenOutside(false)
      .onBegin(() => {
        "worklet";
      })
      .onEnd((event) => {
        "worklet";
        // 如果有宫格被选中，取消宫格选中
        if (selectedCellSV.value !== null) {
          selectedCellSV.value = null;
          selectedRectSV.value = null;
          menuVisibleSV.value = 0;
        }
      })
      .simultaneousWithExternalGesture(
        Gesture.Tap(),
        Gesture.Pan(),
        Gesture.Pinch()
      ); // 允许与所有手势同时工作

    // 容器手势 - 用于检测容器区域点击，取消宫格选中
    const containerGesture = Gesture.Tap()
      .shouldCancelWhenOutside(false)
      .onEnd(() => {
        "worklet";
        // 如果有宫格被选中，取消宫格选中
        if (selectedCellSV.value !== null) {
          selectedCellSV.value = null;
          selectedRectSV.value = null;
          menuVisibleSV.value = 0;
        }
      });

    // 容器布局处理函数
    const handleContainerLayout = (event: any) => {
      const { width, height } = event.nativeEvent.layout;
      if (width > 0 && height > 0) {
        updateCanvasSize(width, height);
      }
    };

    // 图层容器布局处理函数
    const handleLayerContainerLayout = (event: any) => {
      const { width, height } = event.nativeEvent.layout;
      if (width > 0 && height > 0) {
        updateCanvasSize(width, height);
        setLayerContainerSize({ width, height }); // 更新layerContainerSize
      } else {
        console.log("Invalid dimensions, skipping updateCanvasSize");
      }
    };

    // 容器样式
    const containerStyle = [styles.container];

    // 图层容器样式
    const layerContainerStyle = styles.layerContainer;

    // Canvas 样式
    const canvasStyle = [
      styles.canvas,
      {
        backgroundColor:
          canvasState.backgroundColor === "rgba(0,0,0,0)"
            ? "transparent"
            : canvasState.backgroundColor,
        width: canvasState.width,
        height: canvasState.height,
      },
    ];

    // 背景手势层样式
    const backgroundGestureStyle = {
      position: "absolute" as const,
      top: 0,
      left: 0,
      width: canvasState.width,
      height: canvasState.height,
      zIndex: 1, // 最底层，确保能接收到点击事件
    };

    // 计算网格数据（依赖变化自动重算）
    const gridInfo = useMemo(() => {
      const grid = canvasState.gridLayout;
      if (!grid || grid.key === "none")
        return null as null | {
          outerMargin: number;
          spacing: number;
          colWidths: number[];
          rowHeights: number[];
          rows: number;
          cols: number;
        };

      const { rows, cols } = grid;
      const outerMargin = 10;
      const spacing = 10;
      const actualWidth = canvasState.width;
      const actualHeight = canvasState.height;

      const colWeights =
        canvasState.columnWeights && canvasState.columnWeights.length >= cols
          ? canvasState.columnWeights.slice(0, cols)
          : Array.from({ length: cols }, () => 1);
      const rowWeights =
        canvasState.rowWeights && canvasState.rowWeights.length >= rows
          ? canvasState.rowWeights.slice(0, rows)
          : Array.from({ length: rows }, () => 1);

      const sumCol = colWeights.reduce((a: number, b: number) => a + b, 0);
      const sumRow = rowWeights.reduce((a: number, b: number) => a + b, 0);

      const widthAvailable =
        actualWidth - outerMargin * 2 - spacing * (cols - 1);
      const heightAvailable =
        actualHeight - outerMargin * 2 - spacing * (rows - 1);

      const colWidths = colWeights.map(
        (w: number) => (w / sumCol) * widthAvailable
      );
      const rowHeights = rowWeights.map(
        (w: number) => (w / sumRow) * heightAvailable
      );

      return { outerMargin, spacing, colWidths, rowHeights, rows, cols };
    }, [
      canvasState.width,
      canvasState.height,
      canvasState.gridLayout,
      canvasState.columnWeights,
      canvasState.rowWeights,
    ]);

    // 共享值：列宽（按行分开）与行高（按列分开），供手势层实时更新与消费
    const rowColWidthsSV = useSharedValue<number[][]>([]); // [row][col]
    const rowHeightsSV = useSharedValue<number[]>([]); // 仅保留以兼容旧逻辑，网格绘制与手势已切至 colRowHeightsSV
    const colRowHeightsSV = useSharedValue<number[][]>([]); // [col][row]

    // 新增：第一行和第一列的偏移量，用于保持对面边固定
    const firstRowOffsetSV = useSharedValue<number>(0);
    const firstColOffsetSV = useSharedValue<number>(0);

    useEffect(() => {
      if (!gridInfo) return;
      // 初始化：每一行的列宽数组从 gridInfo.colWidths 拷贝一份
      rowColWidthsSV.value = Array.from({ length: gridInfo.rows }, () => [
        ...gridInfo.colWidths,
      ]);
      // 旧的全局行高仍初始化，避免其他地方引用
      rowHeightsSV.value = [...gridInfo.rowHeights];
      // 新的按列存储的行高矩阵：每一列拷贝一份 rowHeights
      colRowHeightsSV.value = Array.from({ length: gridInfo.cols }, () => [
        ...gridInfo.rowHeights,
      ]);
      // 重置偏移量
      firstRowOffsetSV.value = 0;
      firstColOffsetSV.value = 0;
    }, [
      gridInfo,
      rowColWidthsSV,
      rowHeightsSV,
      colRowHeightsSV,
      firstRowOffsetSV,
      firstColOffsetSV,
    ]);

    // 监听待处理图片队列
    useEffect(() => {
      if (pendingImages.length > 0 && !isProcessingImages) {
        setIsProcessingImages(true);

        // 获取当前画布的最大层级（考虑所有图层）
        let currentMaxZ = 2;

        // 顺序处理每张图片，动态更新层级
        const processQueue = async () => {
          for (let index = 0; index < pendingImages.length; index++) {
            const imageZIndex = currentMaxZ + 1;
            const gestureZIndex = currentMaxZ + 1; // 手势层和图片层使用相同层级

            // 直接在这里处理图片，而不是调用 processSingleImage
            try {
              const singleImageData = pendingImages[index];

              // 获取图片尺寸
              const dimensions = await new Promise<{
                width: number;
                height: number;
              }>((resolve) => {
                RNImage.getSize(
                  singleImageData.source,
                  (width: number, height: number) => {
                    console.log("图片真实尺寸:", { width, height });
                    resolve({ width, height });
                  },
                  () => {
                    console.log("获取图片尺寸失败，使用默认尺寸");
                    resolve({ width: 100, height: 100 });
                  }
                );
              });

              // 计算显示尺寸
              const defaultWidth = 100;
              const aspectRatio = dimensions.width / dimensions.height;
              const calculatedHeight = defaultWidth / aspectRatio;
              let finalWidth = singleImageData.width || defaultWidth;
              let finalHeight = singleImageData.height || calculatedHeight;

              // 计算位置（从中心扩散）
              const centerX = canvasState.width / 2;
              const centerY = canvasState.height / 2;
              const radius = 80 + index * 20;
              const angleStep =
                (2 * Math.PI) / Math.max(pendingImages.length, 1);
              const currentAngle = index * angleStep;
              const spreadX = centerX + Math.cos(currentAngle) * radius;
              const spreadY = centerY + Math.sin(currentAngle) * radius;

              let finalX = singleImageData.x || spreadX - finalWidth / 2;
              let finalY = singleImageData.y || spreadY - finalHeight / 2;

              // 限制在画布范围内
              finalX = Math.max(
                0,
                Math.min(finalX, canvasState.width - finalWidth)
              );
              finalY = Math.max(
                0,
                Math.min(finalY, canvasState.height - finalHeight)
              );

              // 计算旋转角度
              const rotationOffset = (index * 15) % 360;

              // 更新画布状态
              setCanvasState((prevState) => {
                // 创建图片层
                const newImageLayer: Layer = {
                  id: generateId(),
                  name: "图片",
                  type: "image",
                  locked: false,
                  visible: true,
                  zIndex: imageZIndex,
                  data: {
                    source: singleImageData.source,
                    x: finalX,
                    y: finalY,
                    width: finalWidth,
                    height: finalHeight,
                    originalWidth: dimensions.width,
                    originalHeight: dimensions.height,
                    scale: 1,
                    rotation: rotationOffset,
                    ...singleImageData,
                  },
                };

                // 创建手势层
                const gestureLayer: Layer = {
                  id: generateId(),
                  name: "手势层",
                  type: "gesture",
                  locked: false,
                  visible: true,
                  zIndex: gestureZIndex,
                  data: {
                    targetLayerId: newImageLayer.id,
                    x: finalX,
                    y: finalY,
                    width: finalWidth,
                    height: finalHeight,
                    rotation: rotationOffset,
                    scale: 1,
                  },
                };

                const newState = {
                  ...prevState,
                  layers: [...prevState.layers, newImageLayer, gestureLayer],
                };

                // 通过 transformSignal 设置初始位置
                layerTransformSignal.value = {
                  layerId: newImageLayer.id,
                  x: finalX,
                  y: finalY,
                  rotation: rotationOffset,
                  scale: 1,
                  timestamp: Date.now(),
                };

                // 保存到历史记录
                const newHistory = history.slice(0, historyIndex + 1);
                newHistory.push(newState);
                setHistory(newHistory);
                setHistoryIndex(newHistory.length - 1);

                return newState;
              });
            } catch (error) {
              console.error(`处理队列中第${index + 1}张图片时出错:`, error);
            }

            // 更新当前最大层级，为下一张图片做准备
            currentMaxZ = gestureZIndex;
          }

          // 清空队列
          setPendingImages([]);
          setIsProcessingImages(false);
        };

        processQueue();
      }
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pendingImages, isProcessingImages, history, historyIndex]);

    // 基于 sharedValue 生成虚线网格路径（与现有视觉一致），UI 线程实时更新
    const rowsConst = gridInfo?.rows ?? 0;
    const colsConst = gridInfo?.cols ?? 0;
    const spacingConst = gridInfo?.spacing ?? 0;
    const outerConst = gridInfo?.outerMargin ?? 0;

    const dashedPathDV = useDerivedValue(() => {
      "worklet";
      if (!rowsConst || !colsConst) return "";
      const dash = 4;
      const gap = 4;
      const widthsMatrix = rowColWidthsSV.value;
      const heightsMatrix = colRowHeightsSV.value;
      const firstRowOffset = firstRowOffsetSV.value || 0;
      const firstColOffset = firstColOffsetSV.value || 0;
      if (!Array.isArray(widthsMatrix) || widthsMatrix.length !== rowsConst)
        return "";
      if (!Array.isArray(heightsMatrix) || heightsMatrix.length !== colsConst)
        return "";

      const createDashed = (x1: number, y1: number, x2: number, y2: number) => {
        "worklet";
        const dx = x2 - x1;
        const dy = y2 - y1;
        const length = Math.hypot(dx, dy);
        if (length === 0) return "";
        const ux = dx / length;
        const uy = dy / length;
        let p = "";
        let cur = 0;
        let cx = x1,
          cy = y1;
        let draw = true;
        while (cur < length) {
          const seg = Math.min(draw ? dash : gap, length - cur);
          if (draw) {
            const nx = cx + ux * seg;
            const ny = cy + uy * seg;
            p += `M ${cx} ${cy} L ${nx} ${ny}`;
            cx = nx;
            cy = ny;
          } else {
            cx += ux * seg;
            cy += uy * seg;
          }
          cur += seg;
          draw = !draw;
        }
        return p;
      };

      // 逐格绘制：x/width 来自每行的列宽；y/height 来自每列的行高
      let path = "";
      for (let r = 0; r < rowsConst; r++) {
        const widths = widthsMatrix[r];
        if (!widths || widths.length !== colsConst) continue;
        let xCursor = outerConst;
        for (let c = 0; c < colsConst; c++) {
          const w = widths[c];
          let x = xCursor;
          // 应用第一列偏移
          if (c === 0) {
            x += firstColOffset;
          }
          const xRight = x + w;
          // 计算该列在第 r 行的 y 与 h
          const colHeights = heightsMatrix[c];
          if (!colHeights || colHeights.length !== rowsConst) {
            xCursor = xRight + spacingConst;
            continue;
          }
          let yStart = outerConst;
          for (let rr = 0; rr < r; rr++)
            yStart += (colHeights[rr] || 0) + spacingConst;
          const h = colHeights[r] ?? 0;
          let y = yStart;
          // 应用第一行偏移
          if (r === 0) {
            y += firstRowOffset;
          }
          const yBottom = y + h;
          path += createDashed(x, y, xRight, y);
          path += createDashed(xRight, y, xRight, yBottom);
          path += createDashed(xRight, yBottom, x, yBottom);
          path += createDashed(x, yBottom, x, y);
          xCursor = xRight + spacingConst;
        }
      }
      return path;
    }, [rowsConst, colsConst, spacingConst, outerConst]);

    // 渲染拼图网格（使用权重计算位置与尺寸）
    const renderGrid = () => {
      if (!canvasState.gridLayout || canvasState.gridLayout.key === "none") {
        return null;
      }

      const info = gridInfo;
      if (!info) return null;

      return (
        <Group>
          <Path
            path={dashedPathDV}
            color="#E5E5E5"
            style="stroke"
            strokeWidth={1}
          />
        </Group>
      );
    };

    // 计算宫格单元（供手势层使用，位置与尺寸与网格一致）
    const renderGridGestureOverlays = () => {
      if (!canvasState.gridLayout || canvasState.gridLayout.key === "none") {
        return null;
      }
      const info = gridInfo;
      if (!info) return null;

      // 使用动态的共享值计算宫格位置和尺寸
      const widthsMatrix = rowColWidthsSV.value;
      const heightsMatrix = colRowHeightsSV.value;
      const firstRowOffset = firstRowOffsetSV.value || 0;

      if (!Array.isArray(widthsMatrix) || !Array.isArray(heightsMatrix)) {
        return null;
      }

      return (
        <>
          {Array.from({ length: info.rows }, (_, row) => {
            // 计算Y坐标：使用当前列的行高数组
            let y = info.outerMargin;
            for (let rr = 0; rr < row; rr++) {
              // 使用第一列的行高作为基准（假设所有列的行高相同）
              const colHeights = heightsMatrix[0] || [];
              y += (colHeights[rr] || 0) + info.spacing;
            }

            // 应用第一行偏移量
            y += firstRowOffset;

            // 使用第一列的行高作为当前行的高度
            const colHeights = heightsMatrix[0] || [];
            const h = colHeights[row] || 0;

            return Array.from({ length: info.cols }, (_, col) => {
              // 计算X坐标：使用当前行的列宽数组
              let x = info.outerMargin;
              const rowWidths = widthsMatrix[row] || [];
              for (let cc = 0; cc < col; cc++) {
                x += (rowWidths[cc] || 0) + info.spacing;
              }

              const w = rowWidths[col] || 0;
              const isSelected =
                selectedGridCell?.row === row && selectedGridCell?.col === col;

              return (
                <GridGestureHandler
                  key={`grid-gesture-${canvasState.gridLayout?.key}-${gridVersion}-${row}-${col}`}
                  gridCell={{ x, y, width: w, height: h, row, col }}
                  isSelected={isSelected}
                  selectedCellSV={selectedCellSV}
                  selectedRectSV={selectedRectSV}
                  doubleTapSignalSV={doubleTapSignalSV}
                  menuVisibleSV={menuVisibleSV}
                  menuXSV={menuXSV}
                  menuYSV={menuYSV}
                  cols={info.cols}
                  rows={info.rows}
                  outerMargin={info.outerMargin}
                  spacing={info.spacing}
                  canvasWidth={canvasState.width}
                  canvasHeight={canvasState.height}
                  rowColWidthsSV={rowColWidthsSV}
                  rowHeightsSV={rowHeightsSV}
                  colRowHeightsSV={colRowHeightsSV}
                  firstRowOffsetSV={firstRowOffsetSV}
                  firstColOffsetSV={firstColOffsetSV}
                />
              );
            });
          })}
        </>
      );
    };

    // 渲染文字图层
    const TextLayer = ({ layer }: { layer: Layer }) => {
      // 使用默认字体，避免require问题
      const font = useFont(null, layer.data.fontSize || 24);

      if (!layer.visible || layer.type !== "text" || !font) return null;

      return (
        <Text
          x={layer.data.x || 0}
          y={layer.data.y || 0}
          text={layer.data.text || "新文字"}
          font={font}
          color={layer.data.color || "#000000"}
        />
      );
    };

    // 渲染贴纸图层
    const StickerLayer = ({ layer }: { layer: Layer }) => {
      // 对于SVG贴纸，我们不使用useImage，而是直接渲染
      const isSvgSticker = layer.data.source?.startsWith("sticker://");

      // 对于普通图像贴纸，使用useImage - 必须在组件顶部调用
      const stickerImage = useImage(isSvgSticker ? null : layer.data.source);

      // 对于SVG贴纸，渲染一个占位符形状
      if (isSvgSticker) {
        console.log("Rendering SVG sticker placeholder");
        return (
          <Rect
            x={layer.data.x || 0}
            y={layer.data.y || 0}
            width={layer.data.width || 100}
            height={layer.data.height || 100}
            color="rgba(0, 122, 255, 0.3)"
            style="fill"
          />
        );
      }

      // 对于普通图像贴纸，检查图像是否加载成功
      if (!stickerImage) {
        console.log("StickerLayer not rendering: no image");
        return null;
      }

      return (
        <Image
          image={stickerImage}
          x={layer.data.x || 0}
          y={layer.data.y || 0}
          width={layer.data.width || 100}
          height={layer.data.height || 100}
        />
      );
    };

    // 渲染图片图层
    const ImageLayer = ({ layer }: { layer: Layer }) => {
      const layerImage = useImage(layer.data.source);
      // 使用 useDerivedValue 创建变换矩阵，与手势层保持一致的变换序列
      const transformMatrix = useDerivedValue(() => {
        const m = Skia.Matrix();
        // 从 layerTransforms 获取当前图层的变换数据
        const transform = layerTransforms.value[layer.id] || {
          x: layer.data.x || 0,
          y: layer.data.y || 0,
          rotation: layer.data.rotation || 0,
          scale: layer.data.scale || 1,
        };

        const width = layer.data.width || 100;
        const height = layer.data.height || 100;
        const x = transform.x;
        const y = transform.y;
        const rotation = transform.rotation;
        const scale = transform.scale;

        // 使用与手势层一致的变换序列：平移→居中→缩放旋转→移回
        // 1. 先平移到手势位置
        m.translate(x, y);
        // 2. 平移到中心点
        m.translate(width / 2, height / 2);
        // 3. 缩放和旋转
        m.scale(scale, scale);
        m.rotate((rotation * Math.PI) / 180);
        // 4. 移回原位置
        m.translate(-width / 2, -height / 2);

        return m;
      });

      return (
        <Group matrix={transformMatrix}>
          <Image
            image={layerImage}
            x={0}
            y={0}
            width={layer.data.width}
            height={layer.data.height}
          />
        </Group>
      );
    };

    // 渲染涂鸦图层
    const DrawingLayer = ({ layer }: { layer: Layer }) => {
      if (!layer.visible || layer.type !== "drawing") return null;

      // 简单的涂鸦显示 - 可以后续扩展为更复杂的绘制功能
      return (
        <Rect
          x={layer.data.x || 0}
          y={layer.data.y || 0}
          width={layer.data.width || 100}
          height={layer.data.height || 100}
          color={layer.data.brushSettings?.color || "rgba(255,0,0,0.3)"}
        />
      );
    };

    // 渲染背景
    const renderBackground = () => {
      return (
        <Group
          clip={{
            x: 0,
            y: 0,
            width: canvasState.width,
            height: canvasState.height,
          }}
        >
          {/* 基础纯色背景始终绘制，保证颜色变更可见 */}
          {canvasState.backgroundColor !== "rgba(0,0,0,0)" && (
            <Rect
              x={0}
              y={0}
              width={canvasState.width}
              height={canvasState.height}
              color={canvasState.backgroundColor}
            />
          )}
          {/* 背景图片 */}
          {canvasState.backgroundImage && backgroundImage && (
            <Image
              image={backgroundImage}
              x={0}
              y={0}
              width={canvasState.width}
              height={canvasState.height}
              fit="cover"
            />
          )}
          {/*   */}
          {canvasState.backgroundGradient && (
            <Rect
              x={0}
              y={0}
              width={canvasState.width}
              height={canvasState.height}
              color={canvasState.backgroundGradient[0]}
            />
          )}
        </Group>
      );
    };

    // 渲染所有图层（仅 Canvas 内的可视内容）
    const renderLayers = () => {
      console.log(
        "renderLayers called, layers count:",
        canvasState.layers.length
      );
      console.log(
        "Layers:",
        canvasState.layers.map((l) => ({
          id: l.id,
          type: l.type,
          visible: l.visible,
        }))
      );

      return canvasState.layers
        .sort((a, b) => a.zIndex - b.zIndex)
        .map((layer) => {
          switch (layer.type) {
            case "text":
              return (
                <Group key={layer.id}>
                  <TextLayer layer={layer} />
                </Group>
              );
            case "sticker":
              return (
                <Group key={layer.id}>
                  <StickerLayer layer={layer} />
                </Group>
              );
            case "image":
              return (
                <Group key={`${layer.id}-${layer.data.x}-${layer.data.y}-${layer.data.rotation}-${layer.data.scale}`}>
                  <ImageLayer layer={layer} />
                </Group>
              );
            case "drawing":
              return (
                <Group key={layer.id}>
                  <DrawingLayer layer={layer} />
                </Group>
              );
            case "gesture":
              // 手势层不需要在 Skia 中渲染，由 UniversalGestureHandler 处理
              return null;
            default:
              console.log("Unknown layer type:", layer.type);
              return null;
          }
        });
    };

    // 渲染图片图层手势
    const renderImageGestures = () => {
      return canvasState.layers
        .sort((a, b) => a.zIndex - b.zIndex)
        .filter((layer) => layer.type === "gesture" && layer.visible)
        .map((layer) => {
          const targetLayer = canvasState.layers.find(
            (l) => l.id === layer.data.targetLayerId
          );

          if (!targetLayer) return null;

          const x = layer.data.x || 0;
          const y = layer.data.y || 0;
          const width = layer.data.width || 300; // 进一步增加默认宽度
          const height = layer.data.height || 300; // 进一步增加默认高度
          const rotation = layer.data.rotation || 0;
          const scale = layer.data.scale || 1;

          console.log("图片手势层:", layer.id, {
            x,
            y,
            width,
            height,
            rotation,
            scale,
            targetLayerId: targetLayer.id,
          });

          return (
            <UniversalGestureHandler
              key={`image-gh-${layer.id}`}
              matrix={layerMatrices[layer.id] || { value: Matrix4() }}
              size={{
                width: width,
                height: height,
                x: x,
                y: y,
              }}
              selectSignal={layerSelectSignal}
              deleteSignal={layerDeleteSignal}
              editSignal={layerEditSignal}
              transformSignal={layerTransformSignal}
              layerId={targetLayer.id}
              debug={true}
              zIndex={targetLayer.zIndex} // 使用图片层的层级，确保手势层和图片层在同一层级
              rotation={rotation}
              scale={scale}
            />
          );
        });
    };

    // 渲染贴纸图层手势
    const renderStickerGestures = () => {
      return canvasState.layers
        .sort((a, b) => a.zIndex - b.zIndex)
        .filter((layer) => layer.type === "sticker" && layer.visible)
        .map((layer) => {
          const x = layer.data.x || 0;
          const y = layer.data.y || 0;
          const width = layer.data.width || 100;
          const height = layer.data.height || 100;

          return (
            <UniversalGestureHandler
              key={`sticker-gh-${layer.id}`}
              matrix={layerMatrices[layer.id] || { value: Matrix4() }}
              size={{
                width: width,
                height: height,
                x: x,
                y: y,
              }}
              selectSignal={layerSelectSignal}
              deleteSignal={layerDeleteSignal}
              editSignal={layerEditSignal}
              layerId={layer.id}
              debug={true} // 启用调试模式，显示手势层
              zIndex={gestureZIndex} // 使用全局手势层层级
            />
          );
        });
    };

    // 渲染文字图层手势
    const renderTextGestures = () => {
      return canvasState.layers
        .sort((a, b) => a.zIndex - b.zIndex)
        .filter((layer) => layer.type === "text" && layer.visible)
        .map((layer) => {
          const x = layer.data.x || 0;
          const y = layer.data.y || 0;
          const width = layer.data.width || 100;
          const height = layer.data.height || 100;

          return (
            <UniversalGestureHandler
              key={`text-gh-${layer.id}`}
              matrix={layerMatrices[layer.id] || { value: Matrix4() }}
              size={{
                width: width,
                height: height,
                x: x,
                y: y,
              }}
              selectSignal={layerSelectSignal}
              deleteSignal={layerDeleteSignal}
              editSignal={layerEditSignal}
              layerId={layer.id}
              debug={true} // 启用调试模式，显示手势层
              zIndex={gestureZIndex} // 使用全局手势层层级
            />
          );
        });
    };

    // 暴露接口
    useImperativeHandle(
      ref,
      () => ({
        // 图层管理
        getLayers: () => canvasState.layers,
        setLayers: (layers: Layer[]) => {
          const newState = { ...canvasState, layers };
          saveToHistory(newState);
        },
        addLayer,
        removeLayer,
        toggleLayerVisibility,
        toggleLayerLock,
        getSelectedLayer,
        selectLayer,

        // 内容添加
        addText,
        addSticker,
        addImage,
        addVideo,

        // 画布操作
        clearCanvas,
        setBackgroundColor,
        setBackgroundImage: (imageUri: string) => {
          const newState = {
            ...canvasState,
            backgroundImage: imageUri,
            backgroundColor: "rgba(0,0,0,0)", // 清除颜色背景
            backgroundGradient: undefined, // 清除渐变背景
            backgroundPattern: undefined, // 清除图案背景
          };
          saveToHistory(newState);
        },
        setBackgroundGradient: (gradient: string[]) => {
          const newState = {
            ...canvasState,
            backgroundGradient: gradient,
            backgroundColor: "rgba(0,0,0,0)", // 清除颜色背景
            backgroundImage: undefined, // 清除图片背景
            backgroundPattern: undefined, // 清除图案背景
          };
          saveToHistory(newState);
        },
        setBackgroundPattern: (pattern: string) => {
          const newState = {
            ...canvasState,
            backgroundPattern: pattern,
            backgroundColor: "rgba(0,0,0,0)", // 清除颜色背景
            backgroundImage: undefined, // 清除图片背景
            backgroundGradient: undefined, // 清除渐变背景
          };
          saveToHistory(newState);
        },
        setCanvasSize,
        setGridLayout,

        // 网格操作（已移除自动填充图片）

        // 层级操作
        moveLayerUp,
        moveLayerDown,
        moveLayerToTop,
        moveLayerToBottom,

        // 编辑操作
        copyLayer,
        deleteLayer,
        transformLayer,

        // 历史记录
        undo,
        redo,
        canUndo: () => historyIndex > 0,
        canRedo: () => historyIndex < history.length - 1,

        // 相框和蒙版操作
        applyFrameToLayer: (layerId: string, frame: any) => {
          // 添加相框图层
          const frameLayer: Omit<Layer, "id" | "zIndex"> = {
            name: "相框",
            type: "image",
            locked: false,
            visible: true,
            data: {
              source: frame.source || "",
              x: canvasState.width / 2,
              y: canvasState.height / 2,
              width: frame.width || 200,
              height: frame.height || 200,
              scale: 1,
              rotation: 0,
              isFrame: true,
              frameData: frame,
            },
          };
          addLayer(frameLayer);
        },
        applyFrameSettingsToLayer: (layerId: string, settings: any) => {
          // 更新相框设置
          transformLayer(layerId, { frameSettings: settings });
        },
        applyMaskToLayer: (layerId: string, mask: any) => {
          console.log("应用蒙版到图层:", layerId, mask);
          // 添加蒙版图层
          const maskLayer: Omit<Layer, "id" | "zIndex"> = {
            name: "蒙版",
            type: "image",
            locked: false,
            visible: true,
            data: {
              source: mask.source || "",
              x: canvasState.width / 2,
              y: canvasState.height / 2,
              width: mask.width || 200,
              height: mask.height || 200,
              scale: 1,
              rotation: 0,
              isMask: true,
              maskData: mask,
            },
          };
          addLayer(maskLayer);
        },
        applyMaskSettingsToLayer: (layerId: string, settings: any) => {
          // 更新蒙版设置
          transformLayer(layerId, { maskSettings: settings });
        },

        // 导出
        exportCanvas,
      }),

      [
        addLayer,
        removeLayer,
        toggleLayerVisibility,
        toggleLayerLock,
        getSelectedLayer,
        selectLayer,
        addText,
        addSticker,
        addImage,
        addVideo,
        clearCanvas,
        setBackgroundColor,
        setCanvasSize,
        setGridLayout,
        moveLayerUp,
        moveLayerDown,
        moveLayerToTop,
        moveLayerToBottom,
        copyLayer,
        deleteLayer,
        transformLayer,
        undo,
        redo,
        historyIndex,
        history.length,
        exportCanvas,
        saveToHistory,
        canvasState,
      ]
    );

    return (
      <>
        <View style={containerStyle} onLayout={handleContainerLayout}>
          {/* 将手势层与 Canvas 分离，避免将 GestureDetector 放入 Canvas 内部/包裹 Canvas */}
          <View
            style={layerContainerStyle}
            onLayout={handleLayerContainerLayout}
          >
            <View style={styles.layerFlexContainer}>
              <View style={styles.canvasContainer}>
                <Canvas ref={canvasRef} style={canvasStyle}>
                  {renderBackground()}
                  {/* 宫格矩形 */}
                  {renderGrid()}
                  {/* 图层 */}
                  {renderLayers()}
                </Canvas>
                {/* 背景手势层 - 用于检测画布空白区域的点击 */}
                <GestureDetector gesture={backgroundGesture}>
                  <View style={backgroundGestureStyle} pointerEvents="auto" />
                </GestureDetector>

                {/* 图片图层手势 */}
                {renderImageGestures()}

                {/* 贴纸图层手势 */}
                {renderStickerGestures()}

                {/* 文字图层手势 */}
                {renderTextGestures()}

                {/* 宫格手势覆盖层（与 Canvas 在同一容器中）*/}
                {renderGridGestureOverlays()}
              </View>
            </View>
          </View>
        </View>

        {/* 画布菜单 */}
        <CanvasMenu
          visible={showCanvasMenu}
          position={menuPosition}
          onClose={() => setShowCanvasMenu(false)}
          onlyKeys={selectedGridCell ? ["photo", "sticker", "text"] : undefined}
          onSelectPhoto={() => {
            setShowCanvasMenu(false);
            // 通过 props 回调通知父组件打开照片选择器
            onCanvasMenuSelect?.("photo");
          }}
          onSelectSticker={() => {
            setShowCanvasMenu(false);
            onCanvasMenuSelect?.("sticker");
          }}
          onSelectBackground={() => {
            setShowCanvasMenu(false);
            onCanvasMenuSelect?.("background");
          }}
          onSelectText={() => {
            setShowCanvasMenu(false);
            onCanvasMenuSelect?.("text");
          }}
        />

        {/* 图层控制按钮 - 移到 Canvas 外部 */}
        {canvasState.selectedLayerId && (
          <LayerControlButtons
            layer={
              canvasState.layers.find(
                (l) => l.id === canvasState.selectedLayerId
              )!
            }
            onDelete={deleteLayer}
            onCopy={copyLayer}
            onLock={toggleLayerLock}
            onVisibility={toggleLayerVisibility}
          />
        )}
      </>
    );
  }
);

FreePuzzleCanvas.displayName = "FreePuzzleCanvas";

const styles = StyleSheet.create({
  container: {
    flex: 1,
    overflow: "hidden",
  },
  canvas: {
    // Remove flex: 1 to allow explicit sizing
    overflow: "hidden",
  },
  controlButtons: {
    position: "absolute",
    backgroundColor: "rgba(0,0,0,0.5)",
    borderRadius: 10,
    padding: 5,
    flexDirection: "row",
    zIndex: 10,
  },
  controlButton: {
    width: 30,
    height: 30,
    justifyContent: "center",
    alignItems: "center",
    marginHorizontal: 2,
  },
  layerContainer: {
    position: "relative",
    width: "100%",
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
  layerFlexContainer: {},
  canvasContainer: {
    position: "relative",
    alignItems: "center",
    justifyContent: "center",
    overflow: "hidden",
  },
  absoluteFillObject: {
    backgroundColor: "rgba(224, 20, 20, 0.5)",
  },
});

export default FreePuzzleCanvas;
